//
//  Home_SettingViewController.m
//  HuaRun2
//
//  Created by admin on 17/9/6.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "Home_SettingViewController.h"
#import "Home_Set_TimeZoneModel.h"
#import "Home_Set_TimeZoneCell.h"
#import "UserModel.h"
#import "NSBundle+Language.h"
#import "BaseTabBarViewController.h"

@interface Home_SettingViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

//value1
@property (nonatomic, strong) UILabel * valueLab1;
//value2
@property (nonatomic, strong) UILabel * valueLab2;
//简体中文
@property (nonatomic, strong) UIButton * zh_CNBtn;
//繁体中文
@property (nonatomic, strong) UIButton * zh_HKBtn;
//英文
@property (nonatomic, strong) UIButton * en_USBtn;
//选择时区
@property (nonatomic, strong) UIView * locationView;
@property (nonatomic, strong) UILabel * locationLab;

@property (nonatomic, strong) UITableView * tableView;
//登陆按钮
@property(nonatomic, strong) UIButton * submitBtn;
//下拉按钮
@property(nonatomic, strong) UIButton * xiaLaBtn;
@end

@implementation Home_SettingViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = NSLocalizedString(@"个人设置", nil);
    self.view.backgroundColor = [UIColor whiteColor];
    
    weakself(ws);
    [self nbRightImageName:@"save" title:nil taget:self clickBlock:^(id result) {
        [ws doneMethod];
    }];
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
    
#pragma mark
- (void)viewInit {
    
    [self.view addSubview:self.valueLab1];
    [self.view addSubview:self.valueLab2];
    
    [self.view addSubview:self.zh_CNBtn];
    [self.view addSubview:self.zh_HKBtn];
    [self.view addSubview:self.en_USBtn];
    
    self.locationView = [self makeLocationView];
    [self.view addSubview:self.locationView];
    [self.view addSubview:self.xiaLaBtn];
    
    [self.view addSubview:self.submitBtn];
    [self.view addSubview: self.tableView];
    
//    weakself(ws);
    _locationView.userInteractionEnabled = NO;
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showChooseLocationView)];
    [_locationView addGestureRecognizer:tap1];
    
//    [_locationView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//        [ws showChooseLocationView];
//    }];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenTableViewMethod)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
}

- (void)hiddenTableViewMethod {
    if (self.tableView.hidden == NO) {
        self.tableView.hidden = YES;
    }
}

    //弹出选择
- (void)showChooseLocationView {
    _tableView.hidden = !_tableView.hidden;
}
    
- (void)dataInit {
    UserModel * userModel = [UserModel getCurrentUserModel];
    _locationLab.text = userModel.timeZone ? userModel.timeZone : @"";
    NSLog(@"%@", userModel);
    if (userModel.language) {
        if ( [userModel.language isEqualToString:@"en_US"] ) {
//            _en_USBtn.selected = YES;
            [self change:_en_USBtn];
        }else if ( [userModel.language isEqualToString:@"zh_HK"] ) {
            
//            _zh_HKBtn.selected = YES;
            [self change:_zh_HKBtn];
        }else if ( [userModel.language isEqualToString:@"zh_CN"] ) {
        
//            _zh_CNBtn.selected = YES;
            [self change:_zh_CNBtn];
        }
    }
}

- (void)layoutInit {
    weakself(ws);
    [self.valueLab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ws.view).offset(64);
        make.left.mas_equalTo(ws.view).offset(kMargin15);
        make.size.mas_equalTo(CGSizeMake(60, 30));
    }];
    
    [self.valueLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ws.valueLab1.mas_bottom).offset(kMargin15);
        make.left.mas_equalTo(ws.valueLab1);
        make.size.mas_equalTo(ws.valueLab1);
    }];
    
    [self.zh_CNBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(ws.valueLab1);
        make.left.mas_equalTo(ws.valueLab1.mas_right).offset(kMargin10 *2);
        make.size.mas_equalTo(CGSizeMake(60, 30));
    }];
    
    [self.zh_HKBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(ws.zh_CNBtn);
        make.left.mas_equalTo(ws.zh_CNBtn.mas_right).offset(kMargin10 * 2);
        make.size.mas_equalTo(ws.zh_CNBtn);
    }];
    
    [self.en_USBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(ws.zh_HKBtn);
        make.left.mas_equalTo(ws.zh_HKBtn.mas_right).offset(kMargin10 * 2);
        make.size.mas_equalTo(ws.zh_CNBtn);
    }];
    
    [self.locationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.zh_CNBtn);
        make.top.mas_equalTo(ws.valueLab2);
        make.right.mas_equalTo(ws.en_USBtn);
        make.height.mas_equalTo(30);
    }];
    
    [self.xiaLaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(ws.locationView.mas_right).offset(-kMargin10);
        make.centerY.mas_equalTo(ws.locationView);
        make.size.mas_equalTo(CGSizeMake(15, 10));
    }];
    
    //tableview 高度显示10条数据
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.locationView);
//        make.bottom.mas_equalTo(ws.view).offset(-48);
        make.top.mas_equalTo(ws.locationView.mas_bottom);
        make.height.mas_equalTo(30 * 6);
    }];
    
    [self.submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view).offset(50);
        make.right.mas_equalTo(ws.view).offset(-50);
        make.top.mas_equalTo(ws.tableView.mas_bottom).offset(kMargin10 * 2);
        make.height.mas_equalTo(40);
    }];

}
    
- (void)methodBind {
    [self fetchTimeZoneList];
}
    
- (void)doneMethod {
    NSString * lang = @"";
    NSString * boundleLange = @"";
    BOOL isZhCN = _zh_CNBtn.isSelected;
    if (isZhCN) {
        lang = @"zh_CN";
        boundleLange = @"zh-Hans";
    }
    BOOL isHK = _zh_HKBtn.isSelected;
    if (isHK) {
        lang = @"zh_HK";
        boundleLange = @"zh-Hant";
    }
    BOOL isEn = _en_USBtn.isSelected;
    if (isEn) {
        lang = @"en_US";
        boundleLange = @"en";
    }
    
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_Set_ChangeTimeZoneUrl];
    
    NSDictionary * dic = @{@"timeZone": [_locationLab.text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                           @"lang": lang};
    weakself(ws);
    
    [ws showActivity:NSLocalizedString(@"正在提交", nil)];
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        
        UserModel * userModel = [UserModel getCurrentUserModel];
        NSDictionary * dic = object[@"obj"];
        userModel.language = dic[@"language"];
        userModel.timeZone = dic[@"timeZone"];
        [UserModel saveUserModel:userModel];

        [ws showAlert:kEditSuccess completionBlock:^{
            [ws changeLanguageTo:boundleLange];
        }];

    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
 
    }];
    
}

#pragma mark 网络请求
- (void)fetchTimeZoneList {
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_Set_TimeZoneListUrl];
    
    NSDictionary * dic = @{@"type": @"timezone"};
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_Set_TimeZoneModel class] json:object[@"obj"]];
        
        ws.dataArray = array;
        
        [ws.tableView reloadData];
        ws.locationView.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
        
    }];
    
}

#pragma mark method
- (UIView * )makeLocationView {
    UIView * view = [UIView new];
    view.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
    view.layer.borderWidth = 1;
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = 5;
    
    UILabel * label = [UILabel new];
    label.textAlignment = NSTextAlignmentLeft;
    label.font = kGeneralFontSize;
    label.textColor = [UIColor colorWithHex:@"3c3c3c"];
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(view);
        make.height.mas_equalTo(view);
        make.left.mas_equalTo(view).offset(kMargin10);
        make.right.mas_equalTo(view).offset(-kMargin10 * 3);
    }];
    
    self.locationLab = label;
    
    return view;
}
    
- (void)change:(UIButton *)btn {
    _zh_CNBtn.selected = NO;
    _zh_HKBtn.selected = NO;
    _en_USBtn.selected = NO;

    _zh_CNBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
    _zh_HKBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
    _en_USBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
    
    btn.selected = !btn.selected;

    btn.layer.borderColor = RGBA(243, 161, 50, 1).CGColor;
}

- (void)changeLanguageTo:(NSString *)language {
    // 设置语言
    [NSBundle setLanguage:language];
    
    // 然后将设置好的语言存储好，下次进来直接加载
    [[NSUserDefaults standardUserDefaults] setObject:language
                                              forKey:@"myLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationResetLanguage object:nil];
    
}

//注销方法
- (void)logoutMethod:(UIButton *)btn {
    [self.view endEditing:YES];
    btn.userInteractionEnabled = NO;
    
    UserModel * userModel = [UserModel getCurrentUserModel];
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kLogoutUrl];
    NSDictionary * dic = @{@"password": userModel.password,
                           @"name": userModel.name,
                           @"refresh_token": userModel.refresh_token};
    
    [self showActivity:NSLocalizedString(@"正在注销",nil)];
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        
        btn.userInteractionEnabled = YES;
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:isLoginState];
        [ws.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationShowLoginVC object:kReLoginStr];
        
        
    } failure:^(NSError *error) {
        [ws hideAllAlert];
        
        btn.userInteractionEnabled = YES;
        
        [ws showWithText:kNetworkError];
    }];
    
}

#pragma mark  UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Home_Set_TimeZoneCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.zoneModel = _dataArray[indexPath.row];
    return cell;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}
    
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    for (int i = 0; i < _dataArray.count; i++) {
        Home_Set_TimeZoneModel * model = _dataArray[i];
        model.isSelectedStatus = NO;
    }
    Home_Set_TimeZoneModel * model = _dataArray[indexPath.row];
    model.isSelectedStatus = YES;
    [tableView reloadData];
    _locationLab.text = [NSString showSpaceStringWithStr: model.value];
    tableView.hidden = YES;
    
}

//是否允许响应手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    //    当点击tableView时不响应手势
    if ([touch.view isDescendantOfView:self.tableView]) {
        return NO;
    }
    
    return YES;
    
}

#pragma mark getter setter
- (UIButton *)zh_CNBtn {
    if (!_zh_CNBtn) {
        self.zh_CNBtn = [UIButton new];
        _zh_CNBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
        _zh_CNBtn.layer.borderWidth = 1;
        _zh_CNBtn.layer.masksToBounds = YES;
        _zh_CNBtn.layer.cornerRadius = 5;
        [_zh_CNBtn setTitle:@"简体中文" forState:(UIControlStateNormal)];
        [_zh_CNBtn setTitleColor: [UIColor colorWithHex:@"3c3c3c"]
                        forState:(UIControlStateNormal)];
        [_zh_CNBtn.titleLabel setFont:kGeneralFontSize];
        [_zh_CNBtn setTitleColor: RGBA(243, 161, 50, 1)
                        forState:(UIControlStateSelected)];
        [_zh_CNBtn addTarget:self action:@selector(change:)
            forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _zh_CNBtn;
}
    
- (UIButton *)zh_HKBtn {
    if (!_zh_HKBtn) {
        self.zh_HKBtn = [UIButton new];
        _zh_HKBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
        _zh_HKBtn.layer.borderWidth = 1;
        _zh_HKBtn.layer.masksToBounds = YES;
        _zh_HKBtn.layer.cornerRadius = 5;
        [_zh_HKBtn setTitle:@"繁體中文" forState:(UIControlStateNormal)];
        [_zh_HKBtn setTitleColor: [UIColor colorWithHex:@"3c3c3c"]
                        forState:(UIControlStateNormal)];
        [_zh_HKBtn setTitleColor: RGBA(243, 161, 50, 1)
                        forState:(UIControlStateSelected)];
        [_zh_HKBtn.titleLabel setFont:kGeneralFontSize];
        [_zh_HKBtn addTarget:self action:@selector(change:)
            forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _zh_HKBtn;
}
    
- (UIButton *)en_USBtn {
    if (!_en_USBtn) {
        self.en_USBtn = [UIButton new];
        _en_USBtn.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
        _en_USBtn.layer.borderWidth = 1;
        _en_USBtn.layer.masksToBounds = YES;
        _en_USBtn.layer.cornerRadius = 5;
        [_en_USBtn setTitle:@"English" forState:(UIControlStateNormal)];
        [_en_USBtn setTitleColor: [UIColor colorWithHex:@"3c3c3c"]
                        forState:(UIControlStateNormal)];
        [_en_USBtn setTitleColor: RGBA(243, 161, 50, 1)
                        forState:(UIControlStateSelected)];
        [_en_USBtn.titleLabel setFont:kGeneralFontSize];
        [_en_USBtn addTarget:self action:@selector(change:)
            forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _en_USBtn;
}
    
    
- (UILabel *)valueLab1 {
    if (!_valueLab1) {
        self.valueLab1 = [UILabel new];
        _valueLab1.textAlignment = NSTextAlignmentRight;
        _valueLab1.font = kGeneralFontSize;
        _valueLab1.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _valueLab1.text = NSLocalizedString(@"语言", nil);
//        _valueLab1.backgroundColor = kRandomColor;
    }
    return _valueLab1;
}
    
- (UILabel *)valueLab2 {
    if (!_valueLab2) {
        self.valueLab2 = [UILabel new];
        _valueLab2.textAlignment = NSTextAlignmentRight;
        _valueLab2.font = kGeneralFontSize;
        _valueLab2.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _valueLab2.text = NSLocalizedString(@"时区", nil);
        //        _valueLab2.backgroundColor = kRandomColor;
    }
    return _valueLab2;
}
    
    
- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[Home_Set_TimeZoneCell class]
           forCellReuseIdentifier:@"cell"];
        _tableView.tableHeaderView = [UIView new];
        _tableView.tableFooterView = [UIView new];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.hidden = YES;
        _tableView.layer.borderColor =  RGBA(195, 202, 205, 1).CGColor;
        _tableView.layer.borderWidth = 1;
        _tableView.layer.masksToBounds = YES;
        _tableView.layer.cornerRadius = 5;
    }
    return _tableView;
}

- (UIButton *)submitBtn {
    if (!_submitBtn) {
        self.submitBtn = [UIButton new];
        _submitBtn.backgroundColor = RGBA(243, 161, 50, 1);
        [_submitBtn setTitle:NSLocalizedString(@"退出", nil)
                    forState:(UIControlStateNormal)];
        _submitBtn.layer.cornerRadius = 5;
        _submitBtn.layer.masksToBounds = YES;
        [_submitBtn addTarget:self action:@selector(logoutMethod:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _submitBtn;
}

- (UIButton *)xiaLaBtn {
    if (!_xiaLaBtn) {
        self.xiaLaBtn = [UIButton new];
        [_xiaLaBtn setBackgroundImage:[UIImage imageNamed:@"save_yanse副本"]
                             forState:(UIControlStateNormal)];
        _xiaLaBtn.userInteractionEnabled = NO;
    }
    return _xiaLaBtn;
}

@end
